from flask import Blueprint, request, jsonify, render_template
from app.models import db, Scene, SceneStep, ApiInfo
import json
from datetime import datetime
from app.controllers.scene_step_helper import create_steps

# 创建蓝图
scene_bp = Blueprint('scene', __name__, url_prefix='/scene')

@scene_bp.route('/')
def list_scenes():
    """场景列表页面"""
    return render_template('scene/index.html')

@scene_bp.route('/list')
def list_scenes_data():
    """场景列表数据接口"""
    scenes = Scene.query.order_by(Scene.name).all()
    return jsonify({'scenes': [scene.to_dict() for scene in scenes]})

@scene_bp.route('/data')
def get_scenes():
    """获取场景列表数据"""
    # 获取查询参数
    search = request.args.get('search', '')
    page = int(request.args.get('page', 1))
    per_page = int(request.args.get('per_page', 10))
    
    # 构建查询
    query = Scene.query
    
    # 搜索过滤
    if search:
        query = query.filter(
            (Scene.name.ilike(f'%{search}%')) |
            (Scene.description.ilike(f'%{search}%'))
        )
    
    # 分页
    pagination = query.order_by(Scene.updated_at.desc()).paginate(page=page, per_page=per_page)
    
    # 构建响应数据
    scenes = [scene.to_dict() for scene in pagination.items]
    
    return jsonify({
        'success': True,
        'data': {
            'scenes': scenes,
            'pagination': {
                'current_page': pagination.page,
                'per_page': pagination.per_page,
                'total_items': pagination.total,
                'total_pages': pagination.pages,
                'start': (pagination.page - 1) * pagination.per_page + 1,
                'end': min(pagination.page * pagination.per_page, pagination.total)
            }
        }
    })


@scene_bp.route('/', methods=['POST'])
def create_scene():
    """创建场景"""
    data = request.json
    if not data:
        return jsonify({
            'success': False,
            'message': '无效的请求数据'
        }), 400
    
    # 创建场景
    scene = Scene(
        name=data.get('name', ''),
        description=data.get('description', ''),
        tags=data.get('tags', [])
    )
    
    db.session.add(scene)
    db.session.flush()  # 获取场景ID
    
    # 创建场景步骤
    steps = data.get('steps', [])
    create_steps(scene.id, steps)
    
    db.session.commit()
    
    return jsonify({
        'success': True,
        'message': '场景创建成功',
        'scene': scene.to_dict()
    })

@scene_bp.route('/<int:scene_id>', methods=['GET'])
def get_scene(scene_id):
    """获取场景详情"""
    scene = Scene.query.get_or_404(scene_id)
    return jsonify({
        'success': True,
        'scene': scene.to_dict()
    })

@scene_bp.route('/<int:scene_id>', methods=['PUT'])
def update_scene(scene_id):
    """更新场景"""
    scene = Scene.query.get_or_404(scene_id)
    data = request.json
    if not data:
        return jsonify({
            'success': False,
            'message': '无效的请求数据'
        }), 400
    
    # 更新场景
    scene.name = data.get('name', scene.name)
    scene.description = data.get('description', scene.description)
    scene.tags = data.get('tags', scene.tags)
    scene.updated_at = datetime.now()
    
    # 删除原有步骤
    SceneStep.query.filter_by(scene_id=scene_id).delete()
    
    # 创建新步骤
    steps = data.get('steps', [])
    create_steps(scene_id, steps)
    
    db.session.commit()
    
    return jsonify({
        'success': True,
        'message': '场景更新成功',
        'scene': scene.to_dict()
    })

@scene_bp.route('/<int:scene_id>', methods=['DELETE'])
def delete_scene(scene_id):
    """删除场景"""
    # 先删除与场景关联的所有步骤
    SceneStep.query.filter_by(scene_id=scene_id).delete()
    
    # 再删除场景本身
    scene = Scene.query.get_or_404(scene_id)
    db.session.delete(scene)
    db.session.commit()
    
    return jsonify({
        'success': True,
        'message': '场景删除成功'
    })